using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(UnityEngine.UI.LoopScrollRect))]
[DisallowMultipleComponent]//避免多个阻止在同一个 GameObject 上附加多个相同类型的组件
public class RollUI : MonoBehaviour, LoopScrollPrefabSource, LoopScrollDataSource
{
    public GameObject item;

    [Header("按钮组")]
    [SerializeField] private Transform sortButtonGroup;
    [SerializeField] private SecondaryButton secondaryButton;
    [Header("Show Panel")]
    [SerializeField] private Image image;
    [SerializeField] private Text  nameText;
    [SerializeField] private Button useButton;

    // Implement your own Cache Pool here. The following is just for example.
    Stack<Transform> pool = new Stack<Transform>();

    private Inventory inventory = new Inventory();
    private LoopScrollRect ls;
    private List<Item> currentItems=new List<Item>();
    private bool isAccendOrder;

    private void Awake()
    {
        ls = GetComponent<LoopScrollRect>();
    }

    void Start()
    {
        Init();

        SecondaryButtonSet("种类", new List<ActionItem>
        {
            new ActionItem("全部",() => InventoryPanel(inventory.items)),
            new ActionItem("道具",() => InventoryPanel(inventory.GetItemKind("道具"))),
            new ActionItem("武器",() => InventoryPanel(inventory.GetItemKind("武器")))
        });
        SecondaryButtonSet("排序", new List<ActionItem>
        {
            new ActionItem
            (
                "数量",() =>{  
                    var sortedByCountAsc =Utility.Sort(currentItems, item => item.ItemInfo.count, isAccendOrder).ToList();
                    InventoryPanel(sortedByCountAsc);
                    isAccendOrder=!isAccendOrder;
                    Debug.Log("按下数量件");
                    }
            )
        });

        InventoryPanel(inventory.items);

    }
    public void InventoryPanel(List<Item> items)
    {
        currentItems= items;
        RefreshData();
    }
    public void ShowPanle(Item item)
    {
        useButton.onClick.RemoveAllListeners();
        nameText.text=item.Data.Name;
        useButton.onClick.AddListener(item.Apply);
    }
    private void Init()
    {
        ls.prefabSource = this;
        ls.dataSource = this;
        //引用
        currentItems=inventory.items;
        RefreshData();
    }
    private void SecondaryButtonSet(string buttonName, List<ActionItem> Actions)
    {
        var clone = Instantiate(secondaryButton.gameObject, sortButtonGroup, false);
        clone.GetComponent<SecondaryButton>().Initialize(Actions);
        clone.GetComponent<SecondaryButton>().PrimaryButton(buttonName);
    }
    #region 接口
    public GameObject GetObject(int index)
    {
        if (pool.Count == 0)
        {
            return Instantiate(item);
        }
        Transform candidate = pool.Pop();
        candidate.gameObject.SetActive(true);
        return candidate.gameObject;
    }
    public void ReturnObject(Transform trans)
    {
        // Use `DestroyImmediate` here if you don't need Pool
        trans.SendMessage("ScrollCellReturn", SendMessageOptions.DontRequireReceiver);
        trans.gameObject.SetActive(false);
        trans.SetParent(transform, false);
        pool.Push(trans);
    }
    /// <summary>
    /// 遍历每个格子
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="idx"></param>
    public void ProvideData(Transform transform, int idx)
    {
        // transform.SendMessage("ScrollCellIndex", idx);
        if (idx<currentItems.Count)
        {
            transform.GetComponent<ItemButton>().Init(currentItems[idx]);
            transform.GetComponent<ItemButton>().UpdateShowPanle(this);
        }
    }
    #endregion
    public void AddItem(Item item)
    {
        inventory.AddItem(item);
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Debug.Log("测试增加物品");
            TestData(0, "张三", "道具", 1);
            TestData(1, "李四", "道具", 12);
            TestData(2, "王五", "道具", 1);
            TestData(3, "赵六", "武器", 10);
            RefreshData();
        }

        if (Input.GetKeyDown(KeyCode.Q))
        {
            Debug.Log("测试增加物品");
            TestData(4, "测试4", "道具", 1);
            TestData(5, "测试5", "道具", 12);
            TestData(6, "测试6", "道具", 1);
            TestData(7, "测试7", "武器", 10);
            RefreshData();
        }
    }
    private void RefreshData()
    {
        ls.totalCount = currentItems.Count;
        //重新填充网格 当格子不够用时
        ls.RefillCells();
        //刷新数据 会重新调用 ProvideData 脚本
        ls.RefreshCells();
    }
    private void TestData(int id, string name, string kinds, int conut)
    {
        ItemData data = new ItemData();
        data.Id = id;
        data.Name=name;
        data.Kinds=kinds;
        Item item = new Item(data);
        item.ItemInfo.count=conut;
        AddItem(item);
    }
}
